package com.bci.pwtz.controller.admin;

/*
 * @FileName: [AbstractController.java]
 * 
 * @Package com.bcinfo.upp.admin.controller
 * 
 * 
 * Copyright (c) 2011-2015 BCINFO Technology Limited Com. All rights reserved.
 * 
 * This software is the confidential and proprietary information of BCINFO
 * Technology Limited Company ("Confidential Information"). You shall not
 * disclose such Confidential Information and shall use it only in accordance
 * with the terms of the contract agreement you entered into with RKY.
 * 
 * $Rev: 3190 $ $LastChangedDate: 2013-11-06 13:33:28 +0800 (星期三, 06 十一月 2013) $
 * $LastChangedBy: fanb $
 * 
 * @category bcinfo-upp
 * 
 * @version 1.1
 * 
 * @author $Author: fanb $
 * 
 * Change History:[Formatter: author date description] <br/> 1 2 3
 */

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.text.ParseException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.PropertiesFactoryBean;

import com.bci.pwtz.admin.service.AdminOperateLogService;
import com.bci.pwtz.exception.PwtzDatabaseException;
import com.bci.pwtz.exception.PwtzException;
import com.bci.pwtz.mysql.model.AdminOperateLog;
import com.bci.pwtz.mysql.model.AdminUser;
import com.bci.pwtz.service.ConfigService;

/**
 * 抽象的控制器 <br/>
 * <p>
 * Description:<br/>
 * <p>
 * 提供公共的控制器方法、属性
 * 
 * <p>
 * For Examples <br/>
 * 
 * <PRE>
 * public class XxxControler extends AbstractController
 * </PRE>
 * <p>
 */
public abstract class AdminAbstractController
{
    protected final Logger            _log      = Logger.getLogger(this.getClass());

    /**
     * @Fields page : 分页页数，默认第一页
     */
    private int                       _page     = 1;

    /**
     * @Fields pageSize : 列表显示数量，默认为10条
     */
    private int                       _pageSize = 10;

    /**
     * @Fields request : 自动注入的HttpServletRequest 变量
     */
    @Autowired
    protected HttpServletRequest      request;

    /**
     * @Fields session : 自动注入的HttpSession变量
     */
    @Autowired
    protected HttpSession             session;

    /**
     * @Fields propertiesFactorBean : properties bean
     */
    @Autowired
    protected PropertiesFactoryBean   _propertiesFactorBean;

    @Autowired
    private ConfigService             configureService;
    
    @Autowired
    private AdminOperateLogService adminOperateLogService;



    /**
     * 获取错误信息 <br/>
     * <p>
     * Description: 通过异常名获取返回的错误信息 <br/>
     * <p>
     * Author: yun<br/>
     * <p>
     * Date: 2013-4-25-上午10:54:20<br/>
     * <p>
     * 
     * @param exceptionName
     * @return 异常对应的错误信息
     * 
     */
    protected String getErrorMessage(String exceptionName)
    {
        try
        {
            return ((Properties) (_propertiesFactorBean.getObject())).getProperty(exceptionName);
        }
        catch (IOException e)
        {
            handleException(e);
            return "错误信息配置文件加载错误";
        }
    }

    protected int getPage()
    {
        String pageString = request.getParameter("page");

        if (StringUtils.isNotBlank(pageString))
        {
            return Integer.parseInt(pageString);
        }

        return _page;
    }

    protected int getPageSize()
    {
        String pageSizeString = request.getParameter("rows");

        if (StringUtils.isNotBlank(pageSizeString))
        {
            return Integer.parseInt(pageSizeString);
        }

        return _pageSize;
    }

    /**
     * 封装ajax返回Map的信息<br/>
     * <p>
     * Description: 将ajax方法返回的Map信息进行统一的封装，使用时只需调用此方法传入参数即可。<br>
     * <p>
     * 如果自定义消息customMsgDesc不为空则使用customMsgDesc，否则根据msgDesc去查找相应的异常信息。 <br/>
     * <p>
     * Author: yun<br/>
     * <p>
     * Date: 2013-6-6-下午2:49:13<br/>
     * <p>
     * 
     * @param opResult
     *            结果
     * @param msgType
     *            消息类型
     * @param msgDesc
     *            消息描述
     * @param customMsgDesc
     *            自定义消息
     * @return
     * 
     */
    protected Map<String, String> packageAjaxReturnMap(String opResult, String msgType, String msgDesc, String customMsgDesc)
    {
        Map<String, String> map = new HashMap<String, String>(10);

        map.put(ERROR_KEY_OP_RESULT, opResult);
        map.put(ERROR_KEY_MSG_TYPE, msgType);

        if (StringUtils.isNotBlank(customMsgDesc))
        {
            map.put(ERROR_KEY_MSG_DESC, customMsgDesc);
        }
        else
        {
            map.put(ERROR_KEY_MSG_DESC, getErrorMessage(msgDesc));
        }

        return map;

    }

    /**
     * 异常封装 <br/>
     * <p>
     * Description: 将繁琐的异常捕获用一个统一的方法来封装并返回封装后的Map <br/>
     * <p>
     * Author: yun<br/>
     * <p>
     * Date: 2013-5-23-下午5:55:10<br/>
     * <p>
     * 
     * @param e
     * @return
     * 
     */
    protected Map<String, String> packageUppException(PwtzException e)
    {
        handleException(e);

        Map<String, String> map = new HashMap<String, String>(4);
        map = packageAjaxReturnMap(ERROR_VALUE_OP_RESULT_FAIL, ERROR_VALUE_MSG_TYPE_ERROR, "", e.getMessage());

        return map;
    }

    /**
     * 异常封装 <br/>
     * <p>
     * Description: 将繁琐的异常捕获用一个统一的方法来封装并返回封装后的Map <br/>
     * <p>
     * Author: yun<br/>
     * <p>
     * Date: 2013-5-23-下午5:55:10<br/>
     * <p>
     * 
     * @param e
     * @return
     * 
     */
    protected Map<String, String> packageException(Exception e)
    {
        handleException(e);

        Map<String, String> map = new HashMap<String, String>(4);

        if (e instanceof ParseException)
        {
            map = packageAjaxReturnMap(ERROR_VALUE_OP_RESULT_FAIL, ERROR_VALUE_MSG_TYPE_ERROR, "ParseException", e.getMessage());
        }
        else
        {
            map = packageAjaxReturnMap(ERROR_VALUE_OP_RESULT_FAIL, ERROR_VALUE_MSG_TYPE_ERROR, "UnknowException", e.getMessage());
        }

        return map;
    }

    /**
     * 普通异常处理 <br/>
     * <p>
     * Description: 记录日志、不封装、不返回对象 <br/>
     * <p>
     * Author: yun<br/>
     * <p>
     * Date: 2013-5-24-上午9:23:52<br/>
     * <p>
     * 
     * @param e
     * 
     */
    protected void handleException(Exception e)
    {
        _log.error(ExceptionUtils.getStackTrace(e));
    }

    /**
     * @Fields ERROR_KEY_MSG_TYPE : 返回值的key msgType
     */
    public static final String ERROR_KEY_MSG_TYPE                 = "msgType";

    /**
     * @Fields ERROR_KEY_MSG_DESC : 返回值的key msgDesc
     */
    public static final String ERROR_KEY_MSG_DESC                 = "msgDesc";

    /**
     * @Fields ERROR_KEY_OP_RESULT : 返回值的key opResult
     */
    public static final String ERROR_KEY_OP_RESULT                = "opResult";

    /**
     * @Fields ERROR_VALUE_MSG_TYPE_INFO : 返回值的value 消息
     */
    public static final String ERROR_VALUE_MSG_TYPE_INFO          = "info";

    /**
     * @Fields ERROR_VALUE_MSG_TYPE_WARN : 返回值的value 警告
     */
    public static final String ERROR_VALUE_MSG_TYPE_WARN          = "warning";

    /**
     * @Fields ERROR_VALUE_MSG_TYPE_QUESTION : 返回值的value 疑问
     */
    public static final String ERROR_VALUE_MSG_TYPE_QUESTION      = "question";

    /**
     * @Fields ERROR_VALUE_MSG_TYPE_ERROR : 返回值的value 错误
     */
    public static final String ERROR_VALUE_MSG_TYPE_ERROR         = "error";

    /**
     * @Fields ERROR_VALUE_OP_RESULT_SUCCESS : 返回值操作结果 成功
     */
    public static final String ERROR_VALUE_OP_RESULT_SUCCESS      = "0";

    /**
     * @Fields ERROR_VALUE_OP_RESULT_FAIL : 返回值操作结果 失败
     */
    public static final String ERROR_VALUE_OP_RESULT_FAIL         = "1";

    /**
     * @Fields ERROR_VALUE_OP_RESULT_SUCCESS_NAME : 获取操作结果 成功字段
     */
    public static final String ERROR_VALUE_OP_RESULT_SUCCESS_NAME = "Success";

    public static final int    add                                = 1;

    public static final int    update                             = 2;

    public static final int    delete                             = 3;


    /**
     * 获取系统配置 <br/>
     * <p>
     * Description: 根据传入的key查询系统配置的值 <br/>
     * <br/>
     * <p>
     * Author: tonic<br/>
     * <p>
     * Date: 2014-9-16-下午2:08:24<br/>
     * <p>
     * 
     * @param key
     * @return
     * @throws PwtzDatabaseException
     * 
     */
    protected String getConfigByKey(String key) throws PwtzDatabaseException
    {
        return configureService.getConfigByKey(key);
    }

    /**
     * 
     * 记录日志 <br/>
     * <p>
     * Description: TODO(详细描述) <br/>
     * <p>
     * Author: tonic<br/>
     * <p>
     * Date: 2014-9-25-上午11:25:02<br/>
     * <p>
     * 
     * @param deviceId
     * @param companyId
     * @param deviceTypeId
     * @param action
     * @param content
     * @param operatorId
     * 
     */
    protected void setLog(int type, String content, Long operatorId)
    {
        AdminOperateLog log = new AdminOperateLog();
        log.setType(type);
        log.setContent(content);
        log.setOperatorId(operatorId);
        log.setCreateTime(new Date());
        try
        {
            adminOperateLogService.add(log);
        }
        catch (PwtzDatabaseException e)
        {
            e.printStackTrace();
        }
    }

    protected AdminUser getUser()
    {
        return (AdminUser) session.getAttribute("adminuser");
    }

    protected Long getUserId()
    {
        return (Long) session.getAttribute("adminuserId");
    }
    public String[] decodeURL(String[] datas) throws UnsupportedEncodingException{
    	if(datas != null && datas.length > 0){
    		for(int i = 0; i < datas.length; i++){
    			if(datas[i] != null && datas.length > 0){
    				datas[i] = URLDecoder.decode(datas[i],"utf-8");
    			}
    		}
    		return datas;
    	}
    	return null;
    }

}